import CryptoJS from 'crypto-js'

// 默认的 KEY 与 iv ，可以和后端商议好，只要统一的给16位字符串即可
const KEY = '1405d337ace8734faba4437e04b61ff3'
const IV = 'ace8734faba4437e'

// AES加密
export function Encrypt(word, keyStr, ivStr) {
    let key = KEY
    let iv = IV
    if (keyStr) {
        key = keyStr
    }

    if (ivStr) {
        iv = ivStr
    }
    key = CryptoJS.enc.Utf8.parse(key)
    if (iv.length > 16) {
        iv = iv.substring(0, 16)
    }
    iv = CryptoJS.enc.Utf8.parse(iv)

    const srcs = CryptoJS.enc.Utf8.parse(word)
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    });

    return CryptoJS.enc.Hex.stringify(encrypted.ciphertext);
}

// AES 解密
export function Decrypt(word, keyStr, ivStr) {
    let key = KEY
    let iv = IV
    if (keyStr) {
        key = keyStr
    }

    if (ivStr) {
        iv = ivStr
    }

    key = CryptoJS.enc.Utf8.parse(key)
    if (iv.length > 16) {
        iv = iv.substring(0, 16)
    }
    iv = CryptoJS.enc.Utf8.parse(iv)
    const base64 = CryptoJS.enc.Hex.parse(word)
    const src = CryptoJS.enc.Base64.stringify(base64)
    var decrypt = CryptoJS.AES.decrypt(src, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding
    });
    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
}
